package com.nw.news.ui;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.nw.news.R;
import com.nw.news.Urls;
import com.nw.news.bean.Notice;
import com.yuan.base.framework.BaseFrameworkActivity;

public class H5Activity extends BaseFrameworkActivity {

	private WebView web_view;
	private TextView tv_title;
	private ProgressBar pb;
	private String url;

	private boolean isError = false;
	private boolean isFirst = true; //判断webview是否加载完成

	@Override
	protected int getLayoutId() {
		return R.layout.activity_h5;
	}

	@Override
	protected void bindViews() {
		tv_title = findViewById(R.id.tv_title);
		web_view = findViewById(R.id.web_view);
		pb = findViewById(R.id.pb);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Notice notice = getIntent().getParcelableExtra("notice");
		if (notice == null) {
			url = Urls.getUrl("/page/agreement.html?version=android");
		} else {
			url = notice.getContent();
			tv_title.setText(notice.getTitle());
		}
		loadWeb();
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void loadWeb() {
		WebSettings webSettings = web_view.getSettings();
		webSettings.setSavePassword(false);
		webSettings.setSaveFormData(false);
		webSettings.setJavaScriptEnabled(true);
		webSettings.setSupportZoom(true);
		webSettings.setBuiltInZoomControls(false);
		webSettings.setUseWideViewPort(true);
		webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);// 设置缓存
//		webSettings.setUseWideViewPort(true);
//		webSettings.setLoadWithOverviewMode(true);
		web_view.setWebChromeClient(new MyWebChromeClient());
		web_view.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				//重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
				if (url.startsWith("tel:") || url.startsWith("mailto:") || url.startsWith("sms:")) {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
					startActivity(intent);
					return true;
				}
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, android.net.http.SslError error) { // 重写此方法可以让webview处理https请求
				handler.proceed();
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				isFirst = false;
				hideProgressBarAtOnce();
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				isFirst = true;
				refreshPB(0, 10);// 开始加载
			}

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				isError = true;
				try {
					view.stopLoading();
				} catch (Exception e) {
					Log.e(TAG, e.toString());
				}
				refreshPB(2, 0);// 加载失败
				showToast("页面加载发生错误");
				closeSelf();
			}
		});
		web_view.loadUrl(url);
	}

	private class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
			final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
			builder.setTitle("提示").setMessage(message).setPositiveButton("确定", null);
			// 不需要绑定按键事件
			// 屏蔽keycode等于84之类的按键
			builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
					Log.v("onJsAlert", "keyCode==" + keyCode + "event=" + event);
					return true;
				}
			});
			// 禁止响应按back键的事件
			builder.setCancelable(false);
			AlertDialog dialog = builder.create();
			dialog.show();
			result.confirm();// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
			return true;
		}

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			if (newProgress >= 100 && !isError) {
				refreshPB(1, 0);
			} else if (newProgress > 10 && newProgress < 100 && !isError) {
				refreshPB(0, newProgress);
			} else if (newProgress <= 10 && !isError) {
				refreshPB(0, 0);
			}
			super.onProgressChanged(view, newProgress);
		}
	}

	private void refreshPB(int what, int progress) {
		runOnUiThread(() -> {
			switch (what) {
				case 0:
					pb.setVisibility(View.VISIBLE);
					pb.setProgress(progress);
					break;
				case 1:
					pb.setVisibility(View.INVISIBLE);
					break;
				case 2:
					pb.setVisibility(View.INVISIBLE);
					break;
				default:
					break;
			}
		});
	}
}
